﻿@page
@using System.Net.Http
@using System.Net.Http.Headers
@using Microsoft.AspNetCore.Authentication
@using System.Text.Json
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <a class="btn btn-primary" href="/Login">Login</a>
    <a class="btn btn-warning" href="/Logout">Logout</a>

    @if (HttpContext.User.Identity != null && HttpContext.User.Identity.IsAuthenticated)
    {
        <ul class="list-group mt-3 text-start">
            <p>Current User</p>
            @foreach (var claim in HttpContext.User.Claims)
            {
                <li class="list-group-item">@claim.Type : @claim.Value</li>
            }
        </ul>

        <ul class="list-group mt-3 text-start">
            <p>oidc</p>
            @{
                var oidc = await HttpContext.AuthenticateAsync("oidc");
                if (oidc.Principal != null)
                {
                    foreach (var claim in oidc.Principal.Claims)
                    {
                        <li class="list-group-item">@claim.Type : @claim.Value</li>
                    }
                }
            }
        </ul>


        <p>HttpContext.GetTokenAsync("access_token")
            <br/>
            @await HttpContext.GetTokenAsync("access_token")
        </p>

        <p>HttpContext.GetTokenAsync("id_token")
            <br/>
            @await HttpContext.GetTokenAsync("id_token")
        </p>

        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44303/api/claims");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await HttpContext.GetTokenAsync("access_token"));

        var response = await client.SendAsync(request);


        <code style="display: block; white-space: pre-wrap; text-align: left">
            @{
                var apiResponse = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    apiResponse = JsonSerializer.Serialize(JsonDocument.Parse(await response.Content.ReadAsStringAsync()), new JsonSerializerOptions
                    {
                        WriteIndented = true
                    });
                }
            }
            @apiResponse;
        </code>
    }
</div>
